package cn.IT.Nf.Test.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库工具类
 */
public class DBUtils {
    private static final String driverClassName;
    private static final String url;
    private static final String username;
    private static final String password;

    static {
        //静态加载properties文件，获取里面的值
        Properties properties = new Properties();
        try {
            InputStream resourceAsStream = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(resourceAsStream);
            if (resourceAsStream != null) {
                resourceAsStream.close();
            }
            driverClassName = properties.getProperty("driverClassName");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接
     *
     * @return 数据库连接
     */
    public static Connection getConnection() {
        Connection connection;
        try {
            if (driverClassName != null && !driverClassName.isEmpty()) {
                Class.forName(driverClassName);
            }
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * 关闭释放资源
     *
     * @param resultSet         释放结果集资源
     * @param preparedStatement 释放预处理资源
     * @param connection        关闭数据库连接
     */
    public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
